package com.gavindon.android.network

import android.system.ErrnoException
import com.gavindon.android.base.MyApplication
import com.gavindon.android.entity.LoginStatus
import com.gavindon.android.utils.SpUtils
import com.gavindon.android.view.start.LoginActivity
import com.gavindon.android.view.start.PreviewWindow
import com.google.gson.JsonSyntaxException
import com.orhanobut.logger.Logger
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import retrofit2.HttpException
import java.io.IOException
import java.lang.Exception
import java.net.ConnectException
import java.net.NoRouteToHostException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import javax.net.ssl.SSLException

/**
 * description:
 * Created by liNan on  2021/5/13 12:48
 */
object ErrorManager {


    fun handleException(exception: Exception) {
        val ex: AppException
        Logger.d(exception.message)
        when (exception) {
            is HttpException -> {
                //401 token错误了
                when {
                    exception.code() == 401 -> {
           /*             try {
                            if (MyApplication.getCurActivity() is PreviewWindow) {
                                return
                            } else if (MyApplication.getCurActivity() !is LoginActivity) {
                                MyApplication.getCurActivity()?.runOnUiThread {
                                    MyApplication.appContext.toast("请重新登录")
                                }
                                SpUtils.clearAll()
                                MyApplication.getCurActivity()?.startActivity<LoginActivity>()
//                                MyApplication.getCurActivity()?.finish()
//                                MyApplication.removeAllActivity()
                            }
                        } catch (exception: Exception) {
                            exception.printStackTrace()
                        }*/
                    }
                    exception.code() == 404 -> {
                        MyApplication.appContext.toast("服务器地址错误-404")
                    }
                    exception.code() == 500 -> {
                        MyApplication.appContext.toast("服务异常,稍候重试!")
                    }
                    else -> {
                        ex = AppException(ERROR.NETWORK_ERROR)
                    }
                }
            }
            is SocketTimeoutException -> {
                //服务器响应的超时
                ex = AppException(ERROR.TIMEOUT_ERROR)
            }
            is ConnectException -> {
                ////连接服务器超时
                ex = AppException(ERROR.NETWORK_ERROR)
            }
            is UnknownHostException -> {
                //未知主机异常
                ex = AppException(ERROR.TIMEOUT_ERROR)
            }
            is NoRouteToHostException -> {
                //无法达到给定ip
                ex = AppException(ERROR.IP_ERROR)
            }
            is SSLException -> {
                //https证书出错
                ex = AppException(ERROR.SSL_ERROR)
            }
            is ErrnoException -> {
                //android.system 系统错误
                ex = AppException(ERROR.NETWORK_ERROR)
            }
            is TokenException -> {
                ex = AppException(ERROR.TOKEN_ERROR)
            }
            is JsonSyntaxException -> {
                ex = AppException(ERROR.JSON_ERROR)
            }
            is ServerMsgError -> {
                StatusException(1, exception.message)
            }
            is IOException -> {
                Logger.d("取消请求")
            }

            else -> {
                ex = AppException(ERROR.UNKNOWN)
            }
        }
    }

    /**
     * 状态错误 非0状态
     */
    class StatusException(status: Int, msg: String?) {

        init {
            when (status) {
                3 -> {
                    MyApplication.appContext.toast(msg.toString())
                }
                1 -> {
                    MyApplication.appContext.toast(msg.toString())
                }
            }
        }

    }

    class AppException : Exception {
        var errorMsg: String
        var errCode: Int = 0

        constructor(errCodeInput: Int, error: String?) : super(error) {
            errorMsg = error ?: "请求失败，请稍后再试"
            errCode = errCodeInput
            MyApplication.appContext.toast(errorMsg)
        }

        constructor(error: ERROR) {
            errCode = error.getKey()
            errorMsg = error.getValue()
            if (errCode != ERROR.UNKNOWN.getKey()) {
                MyApplication.appContext.toast(errorMsg)
            }

        }
    }
}


enum class ERROR(private val code: Int, private val err: String) {

    /**
     * 未知错误
     */
    UNKNOWN(1000, "未知错误"),

    /**
     * 解析错误
     */
    PARSE_ERROR(1001, "解析错误"),

    /**
     * 网络错误
     */
    NETWORK_ERROR(1002, "网络错误,请检查网络是否正常"),

    /**
     * 协议出错
     */
    HTTP_ERROR(1003, "协议出错"),

    /**
     * 证书出错
     */
    SSL_ERROR(1004, "证书出错"),

    /**
     * IP错误不能到达服务器
     */
    IP_ERROR(1005, "IP错误不能到达服务器"),

    /**
     * 连接超时
     */
    TIMEOUT_ERROR(1006, "连接超时,请检查网络是否正常"),

    TOKEN_ERROR(1007, "token异常"),

    JSON_ERROR(1008, "数据异常"),

    AUTH_ERROR(1009, "鉴权错误");


    fun getValue(): String {
        return err
    }

    fun getKey(): Int {
        return code
    }

}